package cn.tedu.micro.demo.order.service.impl;

import cn.tedu.micro.demo.common.pojo.po.OrderInfoPO;
import cn.tedu.micro.demo.common.pojo.protocol.JsonResult;
import cn.tedu.micro.demo.common.pojo.vo.GunInfoVO;
import cn.tedu.micro.demo.order.feign.DeviceClient;
import cn.tedu.micro.demo.order.mapper.OrderInfoMapper;
import cn.tedu.micro.demo.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    //需要一个可以调用device 查询枪接口的客户端对象
    @Autowired
    private DeviceClient deviceClient;
    @Override
    public String orderCreate(Integer gunId, Integer userId) {
        //1.判断枪状态
        checkGunAvailable(gunId);//检查枪可用
        //2.生成billId
        String billId=generateBillId();
        //3.封装po写入数据库
        Integer id=saveOrderInfo(billId,gunId,userId,new Date());
        return billId;
    }

    private Integer saveOrderInfo(String billId, Integer gunId, Integer userId, Date date) {
        //组织po
        OrderInfoPO po=new OrderInfoPO(null,billId,userId,gunId,date,date);
        //baseMapper insert
        orderInfoMapper.insert(po);
        return po.getId();
    }

    private String generateBillId() {
        //demo实现的复杂没有必要 保证唯一
        return UUID.randomUUID().toString();
    }

    private Boolean checkGunAvailable(Integer gunId) {
        log.debug("当前deviceClient实现类:{}",deviceClient.getClass().getName());
        //status=0 空闲可用 非0不可用 抛异常结束
        JsonResult<GunInfoVO> jsonResult = deviceClient.getGunInfo(gunId);
        //解析返回值
        GunInfoVO data = jsonResult.getData();
        //判断非空 且status=1 有一个不满足 抛异常
        if (data!=null&&data.getStatus()==1){
            return true;
        }else{
            throw new RuntimeException("枪状态不可用");
        }
    }

}
